package cn.dida.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.dida.core.Constants;
import cn.dida.model.Company;
import cn.dida.model.HttpResponseBodyWrapper;
import cn.dida.model.Staff;
import cn.dida.model.Sysres;
import cn.dida.model.UserSession;
import cn.dida.service.CompanyService;
import cn.dida.service.RoleService;
import cn.dida.service.StaffService;
import cn.dida.util.AESEncryptor;

import com.alibaba.fastjson.JSONObject;

/**
 * 登录管理
 * 
 * @author weiwei
 *
 */
@Controller
public class LoginController {

	@Autowired
	private StaffService staffService;
	@Autowired
	private CompanyService companyService;

	@Autowired
	private RoleService roleService;

	/**
	 * 进入登录页面
	 * 
	 * @return ModelAndView 登录页面
	 */
	@GetMapping("/login")
	public ModelAndView goLogin() {
		Map<String, Object> model = new HashMap<String, Object>();
		return new ModelAndView("login").addAllObjects(model);
	}

	/**
	 * 进入登录主页
	 * 
	 * @return ModelAndView 登录主页
	 */
	@GetMapping("/loginindex")
	public ModelAndView loginindex() {
		Map<String, Object> model = new HashMap<String, Object>();
		return new ModelAndView("loginindex").addAllObjects(model);
	}

	/**
	 * 登录
	 * 
	 * @param request
	 * @param response
	 * @param account
	 *            用户名
	 * @param pwd
	 *            密码
	 * @param rememberMe
	 *            是否记住我
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@PostMapping("/login")
	public HttpResponseBodyWrapper login(HttpServletRequest request, HttpServletResponse response, String account,
			String pwd, Boolean rememberMe) throws Exception {
		rememberMe = true;

		// 登录验证
		Staff staff = staffService.getStaff(account, pwd);
		if (staff != null) {
			Company company = companyService.getCompany(staff.getCompanyId());
			if (company.getState() == 2 || staff.getState() == 2) {
				// throw new
				// BizzException(BizzException.error_code_invalid_request,
				// "您的账号已禁用");
				return new HttpResponseBodyWrapper(601, null, "您的账号已禁用");
			}

			Date now = new Date();
			if (now.compareTo(company.getEnableTime()) == -1) {
				// throw new
				// BizzException(BizzException.error_code_invalid_request,
				// "您的账号尚未生效，请联系管理员");
				return new HttpResponseBodyWrapper(602, null, "您的账号尚未生效，请联系管理员");
			}
			if (now.compareTo(company.getExpireTime()) == 1) {
				// throw new
				// BizzException(BizzException.error_code_invalid_request,
				// "您的账号已过期，请联系管理员");
				// return new HttpResponseBodyWrapper(result);
				return new HttpResponseBodyWrapper(603, null, "您的账号已过期，请联系管理员");
			}

			UserSession session = new UserSession();
			session.setAccount(staff.getAccount());
			session.setId(staff.getId());
			session.setCompanyId(staff.getCompanyId());
			session.setCompanyName(staff.getCompanyName());

			List<Integer> roleResList = roleService.getRoleResByCompanyId(staff.getCompanyId());

			if (null == roleResList) {
				return new HttpResponseBodyWrapper(601, null, "角色未授权");
			}

			StringBuffer resIds = new StringBuffer();
			// 查询用户权限
			if (staff.getAdmin()) {
				session.setAdmin(true);
				
				for (Integer resid : roleResList) {
					resIds.append(resid + ",");
				}

			} else {
				List<Sysres> staffResList = staffService.getStaffRes(staff.getCompanyId(), staff.getId());
				
				for (Sysres res : staffResList) {
				
					if(roleResList.contains(res.getId())){
						resIds.append(res.getId() + ",");
					}
					
				}

			}

			resIds.append("900,");// 登陆主页
			resIds.append("90,");// 修改密码
			resIds.append("91,");// 修改密码
			resIds.append("92,");// 修改密码
			resIds.append("21");// 个人资料
			session.setResIds(resIds.toString());
			
			Cookie cookie = new Cookie(Constants.PASSPORT_KEY, AESEncryptor.encrytor(JSONObject.toJSONString(session)));
			cookie.setPath("/");
			if (rememberMe != null && rememberMe) {
				// 保存7天
				cookie.setMaxAge(604800);
			}
			response.addCookie(cookie);
			return new HttpResponseBodyWrapper(true);
		} else {
			// throw new BizzException(BizzException.error_code_invalid_params,
			// "账号或密码有误，请重新输入");
			return new HttpResponseBodyWrapper(600, null, "账号或密码有误，请重新输入");
		}

	}

	/**
	 * 注销
	 * 
	 * @param request
	 * @param response
	 * @return 重定向到登录页面
	 * @throws Exception
	 */
	@RequestMapping("/logout")
	public ModelAndView logout(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Cookie cookie = new Cookie(Constants.PASSPORT_KEY, null);
		cookie.setMaxAge(0);
		response.addCookie(cookie);
		response.sendRedirect("/login");
		return null;
	}
}
